package com.test.qpbgboot.base.file;

import com.aliyun.oss.OSS;
import com.test.qpbgboot.base.response.JsonResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@Slf4j
@RestController
@RequestMapping("/v1/file")
@Api(tags = "file module")
public class FileController {

    @Autowired
    private OSS ossClient;
    @Value("${aliyun.oss.bucket-name}")
    private String bucketName;
    @Value("${aliyun.oss.bucket-url}")
    private String bucketUrl;

    @PostMapping("/upload")
    @ApiOperation(value = "文件接收")
    public JsonResult upload(@RequestParam MultipartFile file) throws IOException {
        log.debug("文件接收:file={}", file);
        String fileName = file.getOriginalFilename();
        if (fileName == null) {
            throw new RuntimeException("FileNameError");
        }
        log.debug("原始文件名称:fileName={}", fileName);
        String suffix = fileName.substring(fileName.lastIndexOf("."));
        String newFileName = UUID.randomUUID() + suffix;

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd/");
        String filePath = sdf.format(new Date()) + newFileName;
        InputStream inputStream = file.getInputStream();
        ossClient.putObject(bucketName, filePath, inputStream);
        String url = bucketUrl + "/" + filePath;
        log.debug("文件上传成功，访问地址:url={}", url);
        return JsonResult.success(url);
    }

    @DeleteMapping("/delete")
    @ApiOperation(value = "文件删除")
    public JsonResult delete(
            @RequestParam
            @ApiParam(value = "文件路径", name = "filePath", required = true)
            String filePath) {
        log.debug("文件删除:filePath={}", filePath);
        String path = filePath.replace(bucketUrl + "/", "");
        ossClient.deleteObject(bucketName, path);
        log.debug("文件删除成功！");
        return JsonResult.success();
    }
}
